<template>
  <div class="product-page">
    <!-- 页面头部 -->
    <div class="page-header bg-primary-50">
      <div class="container mx-auto px-4 py-12">
        <h1 class="text-3xl font-bold text-gray-900 mb-4">文创好物</h1>
        <p class="text-gray-600 max-w-2xl">
          精选贵港特色文创产品，传承传统文化，创新设计理念。
        </p>
      </div>
    </div>

    <!-- 主要内容区 -->
    <div class="container mx-auto px-4 py-8">
      <!-- 搜索和筛选区 -->
      <div class="search-filter-section bg-white rounded-lg shadow-sm p-6 mb-8">
        <!-- 搜索框 -->
        <div class="search-box mb-6">
          <FormInput
            v-model="searchQuery"
            placeholder="搜索商品名称或关键词"
            prefix-icon="Search"
            clearable
            @keyup.enter="handleSearch"
          />
        </div>

        <!-- 筛选条件 -->
        <div class="filter-options space-y-4">
          <!-- 商品分类 -->
          <div class="filter-item">
            <div class="filter-label mb-2">商品分类</div>
            <div class="filter-content flex flex-wrap gap-2">
              <el-tag
                v-for="category in categories"
                :key="category.value"
                :type="selectedCategory === category.value ? 'primary' : 'info'"
                class="cursor-pointer"
                @click="handleCategorySelect(category.value)"
              >
                {{ category.label }}
              </el-tag>
            </div>
          </div>

          <!-- 价格区间 -->
          <div class="filter-item">
            <div class="filter-label mb-2">价格区间</div>
            <div class="filter-content flex items-center gap-2">
              <el-input
                v-model="priceRange.min"
                placeholder="最低价"
                class="!w-24"
              />
              <span class="text-gray-400">-</span>
              <el-input
                v-model="priceRange.max"
                placeholder="最高价"
                class="!w-24"
              />
              <el-button @click="handlePriceFilter">确定</el-button>
            </div>
          </div>

          <!-- 排序方式 -->
          <div class="filter-item">
            <div class="filter-label mb-2">排序方式</div>
            <div class="filter-content">
              <el-radio-group v-model="sortBy" class="flex flex-wrap gap-4">
                <el-radio-button label="recommend">推荐排序</el-radio-button>
                <el-radio-button label="sales">销量优先</el-radio-button>
                <el-radio-button label="rating">评分最高</el-radio-button>
                <el-radio-button label="price_asc"
                  >价格从低到高</el-radio-button
                >
                <el-radio-button label="price_desc"
                  >价格从高到低</el-radio-button
                >
              </el-radio-group>
            </div>
          </div>
        </div>
      </div>

      <!-- 商品列表 -->
      <div class="product-list">
        <!-- 列表头部 -->
        <div class="list-header flex items-center justify-between mb-6">
          <div class="total-count text-gray-600">
            共找到
            <span class="text-primary-600 font-medium">{{ total }}</span> 个商品
          </div>
          <div class="view-mode flex items-center space-x-2">
            <el-button-group>
              <el-button
                :type="viewMode === 'grid' ? 'primary' : 'default'"
                @click="viewMode = 'grid'"
              >
                <el-icon><Grid /></el-icon>
              </el-button>
              <el-button
                :type="viewMode === 'list' ? 'primary' : 'default'"
                @click="viewMode = 'list'"
              >
                <el-icon><List /></el-icon>
              </el-button>
            </el-button-group>
          </div>
        </div>

        <!-- 网格视图 -->
        <div
          v-if="viewMode === 'grid'"
          class="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5 gap-6"
        >
          <div
            v-for="product in productList"
            :key="product.id"
            class="product-card group"
          >
            <div class="card-image relative overflow-hidden rounded-lg">
              <el-image
                :src="product.coverImage"
                :alt="product.name"
                class="w-full aspect-square object-cover transition-transform group-hover:scale-105"
              />
              <div class="absolute top-3 right-3 z-10">
                <el-button
                  circle
                  :type="product.isFavorite ? 'danger' : 'default'"
                  @click.stop="handleToggleFavorite(product)"
                >
                  <el-icon>
                    <Star :filled="product.isFavorite" />
                  </el-icon>
                </el-button>
              </div>
            </div>
            <div class="card-content p-4">
              <h3 class="text-lg font-medium mb-2 line-clamp-2">
                {{ product.name }}
              </h3>
              <div class="meta-info text-sm text-gray-500 space-y-1 mb-3">
                <div class="flex items-center justify-between">
                  <div class="rating flex items-center">
                    <el-rate
                      v-model="product.rating"
                      disabled
                      :max="5"
                      :colors="['#ffd21e', '#ffd21e', '#ffd21e']"
                      class="mr-1"
                    />
                    <span class="text-orange-500">{{ product.rating }}</span>
                  </div>
                  <span>{{ product.salesCount }}已售</span>
                </div>
              </div>
              <div class="tags mb-3">
                <el-tag
                  v-for="tag in product.tags.slice(0, 3)"
                  :key="tag"
                  size="small"
                  class="mr-1 mb-1"
                >
                  {{ tag }}
                </el-tag>
              </div>
              <div class="flex items-center justify-between">
                <div class="price">
                  <span class="text-2xl text-primary-600 font-medium">
                    ¥{{ product.price }}
                  </span>
                  <span
                    v-if="product.originalPrice"
                    class="text-sm text-gray-400 line-through ml-2"
                  >
                    ¥{{ product.originalPrice }}
                  </span>
                </div>
                <el-button type="primary" @click="handleViewDetail(product)">
                  查看详情
                </el-button>
              </div>
            </div>
          </div>
        </div>

        <!-- 列表视图 -->
        <div v-else class="space-y-4">
          <div
            v-for="product in productList"
            :key="product.id"
            class="product-item bg-white rounded-lg shadow-sm overflow-hidden group"
          >
            <div class="flex">
              <div class="relative w-64 flex-shrink-0">
                <el-image
                  :src="product.coverImage"
                  :alt="product.name"
                  class="w-full h-full object-cover transition-transform group-hover:scale-105"
                />
                <div class="absolute top-3 right-3 z-10">
                  <el-button
                    circle
                    :type="product.isFavorite ? 'danger' : 'default'"
                    @click.stop="handleToggleFavorite(product)"
                  >
                    <el-icon>
                      <Star :filled="product.isFavorite" />
                    </el-icon>
                  </el-button>
                </div>
              </div>
              <div class="flex-1 p-6">
                <div class="flex items-start justify-between mb-4">
                  <div>
                    <h3 class="text-xl font-medium mb-2">{{ product.name }}</h3>
                    <div class="meta-info text-sm text-gray-500 space-y-1">
                      <div class="flex items-center">
                        <el-rate
                          v-model="product.rating"
                          disabled
                          :max="5"
                          :colors="['#ffd21e', '#ffd21e', '#ffd21e']"
                          class="mr-1"
                        />
                        <span class="text-orange-500 mr-2">{{
                          product.rating
                        }}</span>
                        <span>{{ product.salesCount }}已售</span>
                      </div>
                    </div>
                  </div>
                  <div class="price text-right">
                    <div class="text-2xl text-primary-600 font-medium">
                      ¥{{ product.price }}
                    </div>
                    <div
                      v-if="product.originalPrice"
                      class="text-sm text-gray-400 line-through"
                    >
                      ¥{{ product.originalPrice }}
                    </div>
                  </div>
                </div>
                <div class="description text-gray-600 mb-4 line-clamp-2">
                  {{ product.description }}
                </div>
                <div class="flex items-center justify-between">
                  <div class="tags">
                    <el-tag
                      v-for="tag in product.tags.slice(0, 3)"
                      :key="tag"
                      size="small"
                      class="mr-1"
                    >
                      {{ tag }}
                    </el-tag>
                  </div>
                  <el-button type="primary" @click="handleViewDetail(product)">
                    查看详情
                  </el-button>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 分页 -->
        <div class="pagination flex justify-center mt-8">
          <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :total="total"
            :page-sizes="[20, 40, 60, 80]"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from "vue";
import { useRouter } from "vue-router";
import { ElMessage } from "element-plus";
import { Grid, List, Star } from "@element-plus/icons-vue";
import FormInput from "@/components/global/FormInput.vue";

const router = useRouter();

// 搜索和筛选
const searchQuery = ref("");
const selectedCategory = ref("");
const priceRange = ref({
  min: "",
  max: "",
});
const sortBy = ref("recommend");

// 商品分类
const categories = [
  { label: "全部", value: "" },
  { label: "手工艺品", value: "handicraft" },
  { label: "特色食品", value: "food" },
  { label: "文具用品", value: "stationery" },
  { label: "服饰配饰", value: "clothing" },
  { label: "家居装饰", value: "home" },
  { label: "礼品套装", value: "gift" },
];

// 列表相关
const viewMode = ref("grid");
const currentPage = ref(1);
const pageSize = ref(20);
const total = ref(0);
const productList = ref([
  {
    id: 1,
    name: "贵港特色手工编织包",
    coverImage: "/images/products/bag.jpg",
    description: "采用传统手工编织工艺，结合现代设计元素，既实用又美观。",
    price: 128,
    originalPrice: 168,
    rating: 4.8,
    salesCount: 235,
    tags: ["手工艺品", "热销", "新品"],
    isFavorite: false,
  },
  {
    id: 2,
    name: "贵港特产礼盒",
    coverImage: "/images/products/gift-box.jpg",
    description: "精选贵港特色食品，包装精美，是馈赠亲友的理想选择。",
    price: 198,
    originalPrice: 258,
    rating: 4.9,
    salesCount: 568,
    tags: ["特色食品", "礼品套装", "爆款"],
    isFavorite: true,
  },
]);

// 处理搜索
const handleSearch = () => {
  // TODO: 实现搜索逻辑
  fetchProductList();
};

// 处理分类选择
const handleCategorySelect = (category) => {
  selectedCategory.value = category;
  fetchProductList();
};

// 处理价格筛选
const handlePriceFilter = () => {
  if (priceRange.value.min && priceRange.value.max) {
    if (Number(priceRange.value.min) > Number(priceRange.value.max)) {
      ElMessage.warning("最低价不能大于最高价");
      return;
    }
  }
  fetchProductList();
};

// 处理收藏切换
const handleToggleFavorite = async (product) => {
  try {
    // TODO: 调用收藏/取消收藏API
    product.isFavorite = !product.isFavorite;
    ElMessage.success(product.isFavorite ? "收藏成功" : "已取消收藏");
  } catch (error) {
    ElMessage.error("操作失败，请重试");
  }
};

// 查看商品详情
const handleViewDetail = (product) => {
  router.push(`/product/${product.id}`);
};

// 处理分页大小变更
const handleSizeChange = (size) => {
  pageSize.value = size;
  fetchProductList();
};

// 处理页码变更
const handleCurrentChange = (page) => {
  currentPage.value = page;
  fetchProductList();
};

// 获取商品列表
const fetchProductList = async () => {
  try {
    // TODO: 调用获取商品列表API
    // const { data } = await getProductList({
    //   page: currentPage.value,
    //   pageSize: pageSize.value,
    //   keyword: searchQuery.value,
    //   category: selectedCategory.value,
    //   minPrice: priceRange.value.min,
    //   maxPrice: priceRange.value.max,
    //   sortBy: sortBy.value
    // })
    // productList.value = data.list
    // total.value = data.total
  } catch (error) {
    ElMessage.error("获取商品列表失败");
  }
};

onMounted(() => {
  fetchProductList();
});
</script>

<style lang="scss" scoped>
.product-page {
  .product-card {
    @apply bg-white rounded-lg shadow-sm overflow-hidden transition-shadow hover:shadow-md;
  }

  .product-item {
    .description {
      @apply text-sm leading-relaxed;
    }
  }
}
</style>
